package com.swcw.platform.utils;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.zip.GZIPOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import net.sf.json.JSONObject;

/**
 *
 * @author 杨坚
 * @version [版本号, 2016年2月19日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class CommonUtil {

	private static PropertiesUtil proper = null;

	private static Logger logger = Logger.getLogger(CommonUtil.class);

	// 加载资源文件
	static {
		try {
			proper = new PropertiesUtil();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void printPlatformMsg(HttpServletResponse response, JSONObject msg) {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter pw;
		try {
			pw = response.getWriter();
			pw.write(msg.toString());
			pw.flush();
			pw.close();
		} catch (IOException e) {
			logger.error("response wirter fail!", e);
		}
	}

	/**
	 * 平台返回参数
	 * 
	 * @author 杨坚
	 * @Time 2016年11月11日
	 * @param errCode
	 *            返回码
	 * @return
	 * @throws Exception
	 */
	public static JSONObject printPlatform(Integer errCode) throws Exception {
		JSONObject result = new JSONObject();
		result.put("result", errCode);
		result.put("msg", proper.readValue(String.valueOf(errCode)));
		return result;
	}

	/**
	 * 解析请求数据
	 * 
	 * @param request
	 *            请求信息
	 * 
	 * @author 杨坚
	 * @Time 2016年11月12日
	 * @version 1.0v
	 */
	public static JSONObject analysisRequestMsg(HttpServletRequest request) throws Exception {
		if (StringUtils.isNotEmpty(request.getParameter("params"))) {
			JSONObject params = JSONObject.fromObject(URLDecoder.decode(request.getParameter("params"), "UTF-8"));
			// 分页处理
			int currentPage = 1; // 起始页
			int pageSize = 20;// 每条数
			// 如果前台传过来的参数中有值 则使用前台参数值 否则使用默认值
			if (params.containsKey("currentPage")) {
				currentPage = Integer.parseInt(request.getParameter("currentPage"));
				if (params.containsKey("pageSize")) {
					pageSize = Integer.parseInt(request.getParameter("pageSize"));
				}
				// 自定义分页
				params.put("pageSize", pageSize);
				params.put("currentPage", currentPage);
				// 实体类分页
				params.put("bigenPage", ((currentPage - 1) * pageSize));
				params.put("endPage", pageSize);
			}
			logger.info("《请求平台参数》===========》" + params);
			return params;
		}
		return null;
	}

	/**
	 * 加载本地文件,并转换为byte数组
	 * 
	 * @return
	 */
	public static String loadFile(String path) {
		File file = new File(path);
		FileInputStream fis = null;
		ByteArrayOutputStream baos = null;
		byte[] data = null;
		try {
			fis = new FileInputStream(file);
			baos = new ByteArrayOutputStream((int) file.length());
			byte[] buffer = new byte[1024];
			int len = -1;
			while ((len = fis.read(buffer)) != -1) {
				baos.write(buffer, 0, len);
			}
			data = baos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fis != null) {
					fis.close();
					fis = null;
				}
				baos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return new String(Base64.encodeBase64(compress(data)));
	}

	/**
	 * 对byte[]进行压缩
	 * 
	 * @param 要压缩的数据
	 * @return 压缩后的数据
	 */
	public static byte[] compress(byte[] data) {
		GZIPOutputStream gzip = null;
		ByteArrayOutputStream baos = null;
		byte[] newData = null;
		try {
			baos = new ByteArrayOutputStream();
			gzip = new GZIPOutputStream(baos);
			gzip.write(data);
			gzip.finish();
			gzip.flush();
			newData = baos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				gzip.close();
				baos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return newData;
	}

	/**
	 * 上传图片工具
	 * 
	 * @param file
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public static String uploadUtils(MultipartFile file, HttpServletRequest request) throws IOException {
		// 图片时间戳
		SimpleDateFormat simple = new SimpleDateFormat("yyyyMMdd");
		SimpleDateFormat time = new SimpleDateFormat("yyyyMMddhhmmssSSS");
		String prefix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
		String timestamp = "";
		// 判断文件类型
		if (prefix.equalsIgnoreCase("jpg")) {
			timestamp = time.format(new Date()).concat(".jpg");
		} else if (prefix.equalsIgnoreCase("gif")) {
			timestamp = time.format(new Date()).concat(".gif");
		} else if (prefix.equalsIgnoreCase("bmp")) {
			timestamp = time.format(new Date()).concat(".bmp");
		} else if (prefix.equalsIgnoreCase("png")) {
			timestamp = time.format(new Date()).concat(".png");
		}
		String serverRealPath = request.getSession().getServletContext().getRealPath("")
				.replaceAll(request.getContextPath().substring(1), "");
		String uploadPath = "upload" + File.separator + simple.format(new Date()) + File.separator + prefix;
		// 判断文件路径
		File filePath = new File(serverRealPath + uploadPath);
		if (!filePath.exists() && !filePath.isDirectory()) {
			filePath.mkdirs();
		}

		byte[] bytes = file.getBytes();
		// 写入文件到本地
		BufferedOutputStream stream = new BufferedOutputStream(
				new FileOutputStream(filePath + File.separator + timestamp));
		stream.write(bytes);
		stream.close();
		return "/" + uploadPath + File.separator + timestamp;
	}

	public static void main(String[] args) throws Exception {
		InetAddress addr = InetAddress.getLocalHost();
		System.out.println(addr.getHostAddress());
	}

	/**
	 * 获取xsl数据
	 * 
	 * @throws Exception
	 */
	public void getXsl(HttpServletResponse response, List<String> headList, List<List<String>> contentList)
			throws Exception {
		// 写入excel文件
		Workbook workbook = HttpTool.exportWithExcelFile(headList, contentList);
		try {
			if (workbook != null) {
				response.setHeader("Content-disposition",
						"attachment;filename=" + URLEncoder.encode("punters_data.xls", "UTF-8"));
				response.setContentType("application/msexcel;charset=UTF-8");

				OutputStream out = response.getOutputStream();
				workbook.write(out);
				out.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
